// 并发控制的最大数量
const MAX_CONCURRENT = 4;
// 正在上传的任务数量
let activeTasks = 0;
// 等待上传的任务队列
const pendingTasks = [];
// 已完成的分片数量
let completedChunks = 0;
// 总分片数量
let totalChunksCount = 0;
// 是否已经发送了完成消息的标志
let completionMessageSent = false;

// 执行上传任务
async function processTasks() {
  // 当有等待的任务且活跃任务数小于最大值时，继续处理
  while (pendingTasks.length > 0 && activeTasks < MAX_CONCURRENT) {
    const task = pendingTasks.shift();
    
    activeTasks++;
    
    try {
      const result = await simulateUpload(task);
      // 向主线程发送成功消息
      self.postMessage({
        type: 'chunkComplete',
        data: result
      });
    } catch (error) {
      // 向主线程发送错误消息
      self.postMessage({
        type: 'chunkError',
        data: {
          chunkIndex: task.index,
          error: error.message
        }
      });
    } finally {
      activeTasks--;
    }
  }
  
  // 使用setTimeout让JavaScript事件循环有机会处理其他任务
  setTimeout(() => {
    // 如果没有活跃任务且没有等待任务，表示全部完成，且未发送过完成消息
    if (activeTasks === 0 && pendingTasks.length === 0 && !completionMessageSent) {
      completionMessageSent = true;
      self.postMessage({
        type: 'allComplete',
        data: '所有分片上传完成'
      });
      // 重置计数器，为下一次上传做准备
      resetCounters();
    } else if (pendingTasks.length > 0 && activeTasks < MAX_CONCURRENT) {
      // 如果还有任务未处理，继续处理
      processTasks();
    }
  }, 0);
}

// 重置计数器函数
function resetCounters() {
  completedChunks = 1;
  totalChunksCount = 0;
  completionMessageSent = false;
}

// 模拟上传函数（保持不变）
function simulateUpload({chunk, index, total, name, size, type, uploadId, Authorization, url}) {
  return new Promise((resolve) => {
    let params = new FormData()
    params.append('name', name)
    params.append('size', size)
    params.append('type', type)
    params.append('uploadId', uploadId)
    params.append('directory', 'dy')
    params.append('chunkSize', chunk.size)
    params.append('chunkNumber', index + 1)
    params.append('chunkContent', chunk)
    params.append('totalChunks', total)
    console.log('formData',params.name)
    fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': Authorization,
      },
      body: params
    }).then(response => {
      console.log('接口response', response)
      if(!response.ok) {
        throw new Error('上传失败');
      }
      return response.json()
    }).then(res => {
      // 递增已完成分片数量
      completedChunks++;
      // 基于已完成分片数量计算进度
      const progress = Math.floor((completedChunks / total) * 100);
      resolve({
        success: true,
        chunkIndex: index,
        message: `分片 ${index + 1}/${total} 上传完成`,
        progress: progress,
        completedChunks: completedChunks,
        totalChunks: total,
        fileId: res.data.fileId
      });
    })
  });
}

// 接收来自主线程的消息（保持不变）
onmessage = function(e) {
  console.log('接收到任务', e);
  
  if (e.data.type === 'uploadChunks') {
    // 重置计数器，开始新的上传任务
    resetCounters();
    
    const { chunks, params, Authorization, url } = e.data;
    totalChunksCount = chunks.length;
    
    // 将所有分片添加到任务队列
    chunks.forEach((chunk, index) => {
      pendingTasks.push({
        chunk: chunk,
        index: index+1,
        total: totalChunksCount+1,
        name: params.name,
        size: params.size,
        type: params.type,
        uploadId: params.uploadId,
        Authorization,
        url: url,
      });
    });
    
    // 开始处理任务队列
    processTasks();
  } else if (e.data.type === 'cancel') {
    // 清空任务队列，取消所有待处理的上传
    pendingTasks.length = 0;
    // 重置计数器
    resetCounters();
    self.postMessage({
      type: 'cancelled',
      data: '上传已取消'
    });
  }
};